package com.borderbears.backend;

import java.awt.Frame;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Logger;

import javax.swing.UIManager;
import javax.swing.WindowConstants;

import com.borderbears.backend.connection.ConnectionManager;
import com.borderbears.backend.gui.BCBackendView;
import com.borderbears.backend.util.Config;
import com.borderbears.backend.util.Const;

public class BCBackendApp implements Const.Application {

	private final Logger log = Logger.getLogger(getClass().getName());
	private final Config conf;
	private static BCBackendApp instance;
	private final BCBackendView appFrame;

	public static void main(final String[] args) {

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (final Exception e) {
			e.printStackTrace();
		}

		new BCBackendApp();
	}

	private BCBackendApp() {
		conf = Config.getConfig();
		conf.setFile("BorderCompanyBackend.properties");

		appFrame = BCBackendView.getInstance();
		appFrame.setTitle(conf.get(CONF_APPLICATION_TITLE, "Title"));
		appFrame.setSize(conf.get(CONF_APPLICATION_WIDTH, 500), conf.get(
				CONF_APPLICATION_HEIGHT, 500));
		appFrame.setLocation(conf.get(CONF_APPLICATION_XPOS, 0), conf.get(
				CONF_APPLICATION_YPOS, 0));
		appFrame.addWindowListener(windowAdapter);
		appFrame.addComponentListener(componentAdapter);
		appFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		appFrame.setVisible(true);

		// Do initial stuff

		BCBackendView.getInstance().loadLayout(
				conf.get(CONF_APPLICATION_LAYOUT, "layout.xml"));
		ConnectionManager.getInstance().readConnections(
				conf.get(Const.CONF_CONNECTIONS_FILE, "connections.xml"));

		// new LoadMediaAction().actionPerformed(new ActionEvent(this,0,""));
	}

	private final ComponentAdapter componentAdapter = new ComponentAdapter() {
		@Override
		public void componentResized(final ComponentEvent e) {
			conf.set(CONF_APPLICATION_WIDTH, e.getComponent().getWidth());
			conf.set(CONF_APPLICATION_HEIGHT, e.getComponent().getHeight());
		}

		@Override
		public void componentMoved(final ComponentEvent e) {
			conf.set(CONF_APPLICATION_XPOS, e.getComponent().getX());
			conf.set(CONF_APPLICATION_YPOS, e.getComponent().getY());
		}
	};

	private final WindowAdapter windowAdapter = new WindowAdapter() {
		@Override
		public void windowClosing(final WindowEvent e) {

			BCBackendView.getInstance().saveLayout(
					conf.get(CONF_APPLICATION_LAYOUT, "layout.xml"));

			ConnectionManager.getInstance().storeConnections(
					Config.getConfig().get(Const.CONF_CONNECTIONS_FILE,
							"connections.xml"));

			System.exit(0);
		}

	};

	public static BCBackendApp getApplication() {
		if (null == instance) {
			instance = new BCBackendApp();
		}
		return instance;
	}

	public Frame getMainFrame() {
		return appFrame;
	}

}
